package csu.web.mypetstore.web.servlet;

import csu.web.mypetstore.domain.Account;
import csu.web.mypetstore.service.CartService;
import csu.web.mypetstore.domain.Cart;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
@WebServlet(name = "UpdateCartItemServlet", urlPatterns = {"/updateItemCart"})
public class UpdateCartItemServlet extends HttpServlet {
    private CartService cartService;
    public UpdateCartItemServlet()
    {
        cartService=new CartService();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session= req.getSession();
        Account loginAccount=(Account) session.getAttribute("loginAccount");
        String username=loginAccount.getUsername();
        String itemId=req.getParameter("itemId");
        String quantityStr=req.getParameter("quantity");
        //result视为一个容器
        Map<String,Object> result=new HashMap<>();
        try{
            int quantity=Integer.parseInt(quantityStr);
            cartService.updateCart(username,itemId,quantity);
            Cart cart=cartService.createCart(username);
            session.setAttribute("cart",cart);
            //商品数量小于1，移除商品
            if(quantity<1)
            {
                cartService.removeItem(username,itemId);
                result.put("isRemoved",true);
                result.put("total",0);
            }else {
                //更新商品数量和单一商品总价值
                result.put("isRemoved",false);
                result.put("total",cart.getCartItem(itemId).getTotal().toString());

            }
            //下方总价值
            result.put("subTotal",cart.getSubTotal().toString());
            result.put("valid",true);

        }
        catch (Exception e)
        {
            Cart cart=(Cart)session.getAttribute("cart");
            int quantity=cart.getCartItem(itemId).getQuantity();
            result.put("valid",false);
            result.put("oldQuantity",String.valueOf(quantity));
        }
        //设置json响应
        resp.setContentType("text/json");
        PrintWriter out=resp.getWriter();
        out.println(mapToJson(result));

    }
    // 辅助方法，将Map转换为类似JSON的字符串
    private String mapToJson(Map<String, Object> map) {
        StringBuilder jsonString = new StringBuilder("{");
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            jsonString.append("\"").append(entry.getKey()).append("\":");

            // 检查值是数字还是字符串
            if (entry.getValue() instanceof Number) {
                jsonString.append(entry.getValue());
            } else {
                jsonString.append("\"").append(entry.getValue()).append("\"");
            }

            jsonString.append(",");
        }
        // 移除末尾的逗号
        if (jsonString.length() > 1) {
            jsonString.setLength(jsonString.length() - 1);
        }
        jsonString.append("}");

        return jsonString.toString();
    }
}
